<!--
 * Copyright ©
 * #
 * @author: zw
 * @date: 2024-01-22
 -->

<template>
  <div class="flow-map">
    <div class="flowmap-container" @mousedown="mousedown" @mousemove="mousemove" @mouseup="mouseup">
      <div class="h-full" ref="aerial-map"></div>
    </div>
  </div>
</template>

<script>
import FlowEditor from "@/flow/flowEditor";

export default {
  name: "map",
  props: ["editor"],
  data() {
    return {
      width: 0,
      height: 0,
      sx: 0,
      sy: 0,
      dx: 0,
      dy: 0,
      pos: [],
      drag: false,
    };
  },

  mounted() {
    this.aerialMap = new FlowEditor(this.$refs["aerial-map"]);
    this.aerialMap.offEvent();
  },

  methods: {
    updateMiniMap() {
      this.$nextTick(() => {
        const { editor } = this;
        const el = this.$refs["aerial-map"];
        const { offsetWidth, offsetHeight } = el;
        const aspect = offsetWidth / offsetHeight;

        const data = JSON.stringify(editor.getData());
        const rect = editor.getBoundingRect([...editor.nodes, ...editor.groups, ...editor.edges]);
        const editorAspect = rect.width / rect.height;
        let scale = 1;

        if (editorAspect > aspect) {
          scale = offsetWidth / rect.width;
        } else {
          scale = offsetHeight / rect.height;
        }

        this.aerialMap.init(JSON.parse(data), true);

        this.aerialMap.attr({
          position: [-rect.x * scale, -rect.y * scale],
          scale: [scale, scale],
        });
      });
    },

    mousedown(e) {
      const [x, y] = this.editor.position;
      this.pos = [x, y];
      this.sx = e.offsetX;
      this.sy = e.offsetY;
      this.drag = true;
    },

    mousemove(e) {
      if (!this.drag) return;
      const [x, y] = this.pos;
      this.dx = e.offsetX - this.sx;
      this.dy = e.offsetY - this.sy;
      this.editor.attr({ position: [x - this.dx * 2, y - this.dy * 2] });
    },

    mouseup() {
      this.drag = false;
      this.dx = 0;
      this.dy = 0;
      this.pos = [0, 0];
    },
  },
  //  End
};
</script>

<style lang="css" scoped>
.flow-map {
  width: 260px;
  height: 160px;
  position: absolute;
  right: 0;
  bottom: 0;
  background: #fff;
  z-index: 300;
  border-top: 1px solid #e6e9ed;
}
.flowmap-container {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 6px;
}
#canvas-map {
  width: 100%;
  height: 100%;
}
#canvas-map * {
  cursor: move;
}
</style>
